package com.tengju.user.infrastructure.persistence.redis;

import com.tengju.user.domain.model.login.LoginResult;
import com.tengju.user.domain.model.login.UserType;
import com.tengju.user.infrastructure.persistence.redis.dataobject.RedisKeyObject;
import com.tengju.user.infrastructure.persistence.redis.dataobject.RedisKeyPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

/**
 * @author wuziyang
 */
@Repository
public class LoginTokenCacheRepository {

    @Autowired
    private RedisService redisService;


    /**
     * 存储token
     */
    public boolean cacheToken(String token, String tokenData, long expireTime){

        RedisKeyObject redisKeyObject = new RedisKeyObject(RedisKeyPrefix.LOGIN_TOKEN,token);

        return redisService.setValue(redisKeyObject,tokenData,expireTime, TimeUnit.SECONDS) == 1L;

    }


    /**
     * 获取token
     */
    public LoginResult getToken(String token){

        RedisKeyObject redisKeyObject = new RedisKeyObject(RedisKeyPrefix.LOGIN_TOKEN,token);

        return redisService.get(redisKeyObject, LoginResult.class);

    }


    /**
     * 删除token
     */
    public boolean delToken(String token){

        RedisKeyObject redisKeyObject = new RedisKeyObject(RedisKeyPrefix.LOGIN_TOKEN,token);

        return redisService.delKey(redisKeyObject) == 1;

    }


    /**
     * 删除token
     */
    public boolean delPwdChangeToken(UserType userType, String areaCode, String mobile){

        RedisKeyObject redisKeyObject = new RedisKeyObject(RedisKeyPrefix.PWD_CHANGE, "_" + userType.getVal() + "_" + areaCode + mobile);

        return redisService.delKey(redisKeyObject) == 1;

    }
}
